package com.example.springboot_demo.proxy.dy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class ServiceCglibProxyFactory {
    //保持一个被代理类对象
    private Object target;

    public ServiceCglibProxyFactory(Object target) {
        super();
        this.target = target;
    }

    //方法返回代理类对象
    public Object getProxy() {
        //1.创建生成代理类对象的工具
        Enhancer enhancer = new Enhancer();
        //2.设置父类
        enhancer.setSuperclass(target.getClass());
        //3.设置方法拦截器
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object proxy, Method method, Object[] args, MethodProxy arg3) throws Throwable {
                System.out.println("cglib:开启事务");
                Object result = method.invoke(target, args);
                System.out.println("cglib:提交事务");
                return result;
            }
        });
        //4.生成对象并返回
        return enhancer.create();
    }
}
